// BOSS头目敌机类 - 高效宇宙飞船设计
import { TimeManager } from './TimeManager.js';

export class Boss {
    constructor(x, y, level = 1) {
        this.x = x;
        this.y = y;
        this.width = 150;  // 比精英敌机(50px)大3倍
        this.height = 150;
        this.level = level; // BOSS等级，影响血量和攻击力
        
        // 生命值系统（递增）
        this.maxHp = 100 + (level - 1) * 100; // 初始100，每级增加100
        this.hp = this.maxHp;
        
        // 移动系统（在上半部分随机移动）
        this.targetX = x;
        this.targetY = y;
        this.moveSpeed = 30; // 较慢的移动速度
        this.moveCooldown = 0;
        this.moveInterval = 2000; // 2秒更换一次目标位置
        
        // 射击系统（多样化攻击）
        this.lastShootTime = 0;
        this.shootCooldown = 2000; // 2秒射击一次
        
        // 攻击模式系统
        this.attackModes = ['firework', 'linear', 'fan', 'tracking', 'laser'];
        this.currentAttackMode = 0;
        this.attackModeChangeTime = 0;
        this.attackModeInterval = 8000; // 8秒切换一次攻击模式
        this.consecutiveAttacks = 0; // 连续攻击次数
        this.maxConsecutiveAttacks = 3; // 每种模式最多连续攻击3次
        
        // 激光攻击相关
        this.laserCharging = false;
        this.laserChargeTime = 0;
        this.laserChargeDuration = 1500; // 1.5秒充能
        this.laserSweeping = false;
        this.laserSweepTime = 0;
        this.laserSweepDuration = 2000; // 2秒扫射
        this.laserAngle = -Math.PI / 4; // 激光扫射起始角度
        
        // 死亡系统
        this.isDying = false;
        this.deathWarningTime = 0;
        this.deathWarningDuration = 1500; // 1.5秒前摇警告
        this.explosionTriggered = false;
        
        // 视觉特效（简化）
        this.enginePulse = 0;
        this.shieldPulse = 0;
        this.damageFlash = 0;
        
        // 边界限制（只在上半部分活动）
        this.minY = 50;
        this.maxY = 250;
        this.minX = 75; // 考虑BOSS尺寸的边界
        this.maxX = 525; // 画布宽度600 - BOSS宽度75
        
        // 预计算路径点，减少计算消耗
        this.shipVertices = this.calculateShipVertices();
    }
    
    // 预计算飞船顶点，避免每帧计算
    calculateShipVertices() {
        const centerX = this.width / 2;
        const centerY = this.height / 2;
        
        return [
            {x: centerX, y: 10},                           // 船头
            {x: this.width * 0.8, y: this.height * 0.3},  // 右上
            {x: this.width * 0.9, y: this.height * 0.7},  // 右下
            {x: this.width * 0.7, y: this.height * 0.9},  // 右底
            {x: this.width * 0.3, y: this.height * 0.9},  // 左底
            {x: this.width * 0.1, y: this.height * 0.7},  // 左下
            {x: this.width * 0.2, y: this.height * 0.3}   // 左上
        ];
    }
    
    update(deltaTime, canvasWidth, canvasHeight) {
        // 如果正在死亡过程中
        if (this.isDying) {
            return this.updateDeathSequence(deltaTime);
        }
        
        // 更新攻击模式
        this.updateAttackMode(deltaTime);
        
        // 更新移动目标
        this.updateMovement(deltaTime, canvasWidth);
        
        // 更新位置
        this.updatePosition(deltaTime);
        
        // 更新视觉特效
        this.updateEffects(deltaTime);
        
        // 更新激光攻击状态
        this.updateLaserAttack(deltaTime);
        
        // 更新受伤闪烁
        if (this.damageFlash > 0) {
            this.damageFlash = TimeManager.updateTimer(this.damageFlash, deltaTime);
        }
        
        return null; // 正常状态返回null
    }
    
    updateMovement(deltaTime, canvasWidth) {
        this.moveCooldown = TimeManager.updateTimer(this.moveCooldown, deltaTime);
        
        if (TimeManager.isTimeUp(this.moveCooldown)) {
            // 选择新的目标位置（在上半部分）
            this.targetX = Math.random() * (this.maxX - this.minX) + this.minX;
            this.targetY = Math.random() * (this.maxY - this.minY) + this.minY;
            this.moveCooldown = this.moveInterval;
        }
    }
    
    updatePosition(deltaTime) {
        // 平滑移动到目标位置
        const dx = this.targetX - this.x;
        const dy = this.targetY - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance > 5) {
            const moveX = (dx / distance) * this.moveSpeed * (deltaTime / 1000);
            const moveY = (dy / distance) * this.moveSpeed * (deltaTime / 1000);
            
            this.x += moveX;
            this.y += moveY;
            
            // 确保不超出边界
            this.x = Math.max(this.minX, Math.min(this.maxX, this.x));
            this.y = Math.max(this.minY, Math.min(this.maxY, this.y));
        }
    }
    
    updateEffects(deltaTime) {
        // 简化的特效更新
        this.enginePulse = TimeManager.updatePhase(this.enginePulse, deltaTime, 6);
        this.shieldPulse = TimeManager.updatePhase(this.shieldPulse, deltaTime, 3);
    }
    
    // 攻击模式更新
    updateAttackMode(deltaTime) {
        this.attackModeChangeTime += deltaTime;
        
        // 检查是否需要切换攻击模式
        if (this.attackModeChangeTime >= this.attackModeInterval || 
            this.consecutiveAttacks >= this.maxConsecutiveAttacks) {
            this.switchAttackMode();
        }
    }
    
    // 切换攻击模式
    switchAttackMode() {
        this.currentAttackMode = (this.currentAttackMode + 1) % this.attackModes.length;
        this.attackModeChangeTime = 0;
        this.consecutiveAttacks = 0;
        
        // 重置激光攻击状态
        this.laserCharging = false;
        this.laserSweeping = false;
        this.laserChargeTime = 0;
        this.laserSweepTime = 0;
        
        console.log(`BOSS切换到攻击模式: ${this.attackModes[this.currentAttackMode]}`);
    }
    
    // 激光攻击更新
    updateLaserAttack(deltaTime) {
        if (this.attackModes[this.currentAttackMode] !== 'laser') return;
        
        if (!this.laserCharging && !this.laserSweeping) {
            // 开始激光充能
            this.laserCharging = true;
            this.laserChargeTime = 0;
            console.log('BOSS 开始激光充能');
        } else if (this.laserCharging) {
            // 激光充能中
            this.laserChargeTime += deltaTime;
            if (this.laserChargeTime >= this.laserChargeDuration) {
                this.laserCharging = false;
                this.laserSweeping = true;
                this.laserSweepTime = 0;
                this.laserAngle = -Math.PI / 4; // 重置扫射角度
                console.log('BOSS 激光充能完成，开始扫射');
            }
        } else if (this.laserSweeping) {
            // 激光扫射中
            this.laserSweepTime += deltaTime;
            const sweepProgress = this.laserSweepTime / this.laserSweepDuration;
            this.laserAngle = -Math.PI / 4 + sweepProgress * (Math.PI / 2); // 从-45度到45度
            
            if (this.laserSweepTime >= this.laserSweepDuration) {
                this.laserSweeping = false;
                this.consecutiveAttacks++;
                console.log('BOSS 激光扫射完成');
            }
        }
    }
    
    updateDeathSequence(deltaTime) {
        if (!this.explosionTriggered) {
            this.deathWarningTime += deltaTime;
            
            if (this.deathWarningTime >= this.deathWarningDuration) {
                this.explosionTriggered = true;
                return 'explode'; // 通知游戏创建爆炸
            }
        }
        return null;
    }
    
    // 受击处理
    takeDamage(damage = 1) {
        if (this.isDying) return false;
        
        this.hp -= damage;
        this.damageFlash = 400; // 400毫秒闪烁效果
        
        if (this.hp <= 0) {
            this.startDeathSequence();
            return true; // BOSS开始死亡序列
        }
        return false;
    }
    
    startDeathSequence() {
        this.isDying = true;
        this.deathWarningTime = 0;
        this.explosionTriggered = false;
    }
    
    // 检查是否可以射击
    canShoot() {
        const currentTime = Date.now();
        if (currentTime - this.lastShootTime >= this.shootCooldown) {
            this.lastShootTime = currentTime;
            this.consecutiveAttacks++; // 增加连续攻击计数
            return true;
        }
        return false;
    }

    // 根据当前攻击模式创建子弹
    createBullets(playerX, playerY) {
        const currentMode = this.attackModes[this.currentAttackMode];
        
        switch (currentMode) {
            case 'firework':
                return this.createFireworkBullets();
            case 'linear':
                return this.createLinearBullets(playerX, playerY);
            case 'fan':
                return this.createFanBullets();
            case 'tracking':
                return this.createTrackingMissiles(playerX, playerY);
            case 'laser':
                return this.createLaserAttack();
            default:
                return this.createFireworkBullets();
        }
    }

    // 烟花式射击（优化版，降低速度）
    createFireworkBullets() {
        const bullets = [];
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height;
        
        // 创建多个方向的子弹（烟花效果）
        const bulletCount = 12 + this.level * 2; // 减少数量：基础12发，每级增加2发
        const angleStep = (Math.PI * 2) / bulletCount;
        
        for (let i = 0; i < bulletCount; i++) {
            const angle = angleStep * i;
            const speed = 1.8; // 降低速度：从3降到1.8
            const vx = Math.cos(angle) * speed;
            const vy = Math.sin(angle) * speed;
            
            bullets.push({
                x: centerX - 2,
                y: centerY,
                vx: vx,
                vy: vy,
                type: 'boss'
            });
        }
        
        return bullets;
    }

    // 直线弹幕攻击（朝玩家方向密集射击）
    createLinearBullets(playerX, playerY) {
        const bullets = [];
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height;
        
        // 计算朝向玩家的角度
        const dx = playerX - centerX;
        const dy = playerY - centerY;
        const angle = Math.atan2(dy, dx);
        
        // 创建5发直线子弹，稍微分散角度
        const bulletCount = 5;
        const spreadAngle = Math.PI / 12; // 15度扩散
        
        for (let i = 0; i < bulletCount; i++) {
            const offsetAngle = angle + (i - 2) * (spreadAngle / 2);
            const speed = 2.2; // 较慢的速度让玩家有反应时间
            const vx = Math.cos(offsetAngle) * speed;
            const vy = Math.sin(offsetAngle) * speed;
            
            bullets.push({
                x: centerX - 2,
                y: centerY,
                vx: vx,
                vy: vy,
                type: 'boss'
            });
        }
        
        return bullets;
    }

    // 扇形弹幕攻击（向前方扇形区域密集射击）
    createFanBullets() {
        const bullets = [];
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height;
        
        // 扇形角度范围：向下的90度扇形
        const startAngle = Math.PI * 0.25; // 45度
        const endAngle = Math.PI * 0.75;   // 135度
        const bulletCount = 8;
        const angleStep = (endAngle - startAngle) / (bulletCount - 1);
        
        for (let i = 0; i < bulletCount; i++) {
            const angle = startAngle + i * angleStep;
            const speed = 1.9; // 扇形弹幕速度
            const vx = Math.cos(angle) * speed;
            const vy = Math.sin(angle) * speed;
            
            bullets.push({
                x: centerX - 2,
                y: centerY,
                vx: vx,
                vy: vy,
                type: 'boss'
            });
        }
        
        return bullets;
    }

    // 追踪导弹攻击（发射会跟踪玩家的慢速导弹）
    createTrackingMissiles(playerX, playerY) {
        const missiles = [];
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height;
        
        // 发射2-3枚追踪导弹
        const missileCount = 2 + Math.floor(this.level / 2);
        
        console.log(`创建 ${missileCount} 枚追踪导弹，目标位置: (${playerX}, ${playerY})`);
        
        for (let i = 0; i < missileCount; i++) {
            // 初始方向朝向玩家，但速度较慢
            const dx = playerX - centerX;
            const dy = playerY - centerY;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance > 0) {
                const speed = 1.2; // 很慢的初始速度
                const vx = (dx / distance) * speed;
                const vy = (dy / distance) * speed;
                
                missiles.push({
                    x: centerX - 2 + (i - 1) * 20, // 稍微分散发射位置
                    y: centerY,
                    vx: vx,
                    vy: vy,
                    type: 'boss',
                    isTracking: true, // 标记为追踪导弹
                    targetX: playerX,
                    targetY: playerY,
                    trackingStrength: 0.8, // 追踪强度
                    maxSpeed: 2.0 // 最大速度限制
                });
            }
        }
        
        return missiles;
    }

    // 激光扫射攻击（创建激光而不是子弹）
    createLaserAttack() {
        // 激光攻击不返回子弹，而是通过激光系统处理
        // 这里返回空数组，实际激光由updateLaserAttack方法处理
        return [];
    }

    // 获取当前激光信息（供游戏主循环调用）
    getLaserInfo() {
        if (this.attackModes[this.currentAttackMode] === 'laser' && (this.laserCharging || this.laserSweeping)) {
            const centerX = this.x + this.width / 2;
            const centerY = this.y + this.height / 2;
            
            return {
                x: centerX,
                y: centerY,
                angle: this.laserAngle,
                length: 400, // 激光长度
                charging: this.laserCharging,
                sweeping: this.laserSweeping
            };
        }
        return null;
    }

    render(ctx) {
        ctx.save();
        
        // 死亡警告效果
        if (this.isDying && !this.explosionTriggered) {
            this.renderDeathWarning(ctx);
        }
        
        // 如果爆炸已经触发，不再渲染BOSS机身
        if (this.explosionTriggered) {
            ctx.restore();
            return;
        }
        
        // 受伤闪烁效果
        if (this.damageFlash > 0 && Math.floor(Date.now() / 100) % 2 === 0) {
            ctx.globalAlpha = 0.5;
        }
        
        // 绘制高效的宇宙飞船
        this.renderSpaceshipBody(ctx);
        this.renderSpaceshipEngines(ctx);
        this.renderSpaceshipWeapons(ctx);
        this.renderSpaceshipShield(ctx);
        
        // 绘制生命值条
        this.renderHealthBar(ctx);
        
        ctx.restore();
    }
    
    renderDeathWarning(ctx) {
        // 红色警告闪烁
        const warningProgress = this.deathWarningTime / this.deathWarningDuration;
        const flashSpeed = 10 + warningProgress * 20; // 加速闪烁
        const alpha = 0.3 + Math.sin(Date.now() / (1000 / flashSpeed)) * 0.3;
        
        ctx.fillStyle = `rgba(255, 0, 0, ${alpha})`;
        ctx.fillRect(this.x - 50, this.y - 50, this.width + 100, this.height + 100);
        
        // 警告文字
        ctx.fillStyle = `rgba(255, 255, 0, ${alpha})`;
        ctx.font = 'bold 24px Arial';
        ctx.textAlign = 'center';
        ctx.fillText('WARNING!', this.x + this.width/2, this.y - 60);
        ctx.fillText('EXPLOSION IMMINENT!', this.x + this.width/2, this.y - 30);
    }
    
    renderSpaceshipBody(ctx) {
        // 主船体 - 使用预计算的顶点和简单渐变
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height / 2;
        
        // 简化的主体渐变
        const bodyGradient = ctx.createLinearGradient(this.x, this.y, this.x, this.y + this.height);
        bodyGradient.addColorStop(0, '#666666');
        bodyGradient.addColorStop(0.5, '#888888');
        bodyGradient.addColorStop(1, '#555555');
        
        ctx.fillStyle = bodyGradient;
        
        // 使用预计算的顶点绘制主舰体
        ctx.beginPath();
        for (let i = 0; i < this.shipVertices.length; i++) {
            const vertex = this.shipVertices[i];
            const x = this.x + vertex.x;
            const y = this.y + vertex.y;
            
            if (i === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        ctx.closePath();
        ctx.fill();
        
        // 简化的船体边框
        ctx.strokeStyle = '#ffaa44';
        ctx.lineWidth = 2;
        ctx.stroke();
        
        // 中央控制室（简化）
        ctx.fillStyle = '#0088ff';
        ctx.beginPath();
        ctx.arc(centerX, centerY, 15, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.strokeStyle = '#00aaff';
        ctx.lineWidth = 1;
        ctx.stroke();
        
        // 控制室窗口
        const pulse = 0.7 + Math.sin(this.enginePulse * 2) * 0.3;
        ctx.fillStyle = `rgba(255, 255, 255, ${pulse})`;
        ctx.beginPath();
        ctx.arc(centerX, centerY - 3, 2, 0, Math.PI * 2);
        ctx.fill();
    }
    
    renderSpaceshipEngines(ctx) {
        // 简化的三引擎系统
        const pulse = 0.8 + Math.sin(this.enginePulse) * 0.2;
        const enginePositions = [0.2, 0.5, 0.8]; // 引擎位置比例
        
        for (let i = 0; i < enginePositions.length; i++) {
            const engineX = this.x + this.width * enginePositions[i];
            const engineY = this.y + this.height - 5;
            const engineWidth = 12;
            const flameLength = 20 + Math.sin(this.enginePulse + i) * 5;
            
            // 引擎喷射效果
            const engineGradient = ctx.createLinearGradient(
                engineX, engineY, engineX, engineY + flameLength
            );
            engineGradient.addColorStop(0, `rgba(255, 255, 255, ${pulse})`);
            engineGradient.addColorStop(0.4, `rgba(0, 150, 255, ${pulse * 0.7})`);
            engineGradient.addColorStop(1, 'rgba(0, 50, 100, 0)');
            
            ctx.fillStyle = engineGradient;
            ctx.fillRect(engineX - engineWidth/2, engineY, engineWidth, flameLength);
            
            // 引擎本体
            ctx.fillStyle = '#333333';
            ctx.fillRect(engineX - 4, engineY - 3, 8, 6);
        }
    }
    
    renderSpaceshipWeapons(ctx) {
        // 简化的武器系统
        const weaponPulse = 0.7 + Math.sin(this.enginePulse * 1.5) * 0.3;
        const isCharging = Date.now() - this.lastShootTime < 500;
        
        // 侧翼武器
        const weaponPositions = [
            {x: this.x + this.width * 0.15, y: this.y + this.height * 0.4},
            {x: this.x + this.width * 0.85, y: this.y + this.height * 0.4}
        ];
        
        for (let pos of weaponPositions) {
            // 武器管
            ctx.fillStyle = '#555555';
            ctx.fillRect(pos.x - 6, pos.y, 12, 30);
            
            // 武器边框
            ctx.strokeStyle = '#888888';
            ctx.lineWidth = 1;
            ctx.strokeRect(pos.x - 6, pos.y, 12, 30);
            
            // 充能效果
            if (isCharging) {
                ctx.fillStyle = `rgba(255, 100, 0, ${weaponPulse})`;
                ctx.fillRect(pos.x - 4, pos.y + 26, 8, 2);
            }
        }
        
        // 主炮
        const mainGunX = this.x + this.width * 0.5;
        const mainGunY = this.y + this.height * 0.25;
        
        ctx.fillStyle = '#666666';
        ctx.fillRect(mainGunX - 8, mainGunY, 16, 40);
        
        ctx.strokeStyle = '#999999';
        ctx.lineWidth = 1;
        ctx.strokeRect(mainGunX - 8, mainGunY, 16, 40);
        
        // 主炮充能
        if (isCharging) {
            ctx.fillStyle = `rgba(255, 255, 0, ${weaponPulse})`;
            ctx.fillRect(mainGunX - 6, mainGunY + 36, 12, 3);
        }
    }
    
    renderSpaceshipShield(ctx) {
        // 简化的护盾系统
        const pulse = 0.4 + Math.sin(this.shieldPulse) * 0.2;
        const centerX = this.x + this.width / 2;
        const centerY = this.y + this.height / 2;
        const shieldRadius = this.width * 0.55;
        
        // 护盾环
        ctx.strokeStyle = `rgba(0, 200, 255, ${pulse})`;
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(centerX, centerY, shieldRadius, 0, Math.PI * 2);
        ctx.stroke();
        
        // 护盾发生器指示点
        const generatorCount = 4;
        for (let i = 0; i < generatorCount; i++) {
            const angle = (i / generatorCount) * Math.PI * 2;
            const genX = centerX + Math.cos(angle) * 25;
            const genY = centerY + Math.sin(angle) * 25;
            
            ctx.fillStyle = `rgba(0, 255, 200, ${pulse + 0.3})`;
            ctx.beginPath();
            ctx.arc(genX, genY, 2, 0, Math.PI * 2);
            ctx.fill();
        }
    }
    
    renderHealthBar(ctx) {
        // BOSS生命值条（保持不变）
        const barWidth = this.width;
        const barHeight = 8;
        const barX = this.x;
        const barY = this.y - 20;
        
        // 背景
        ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
        ctx.fillRect(barX, barY, barWidth, barHeight);
        
        // 生命值
        const healthPercent = this.hp / this.maxHp;
        let healthColor = '#ff0000';
        if (healthPercent > 0.6) healthColor = '#ffaa00';
        else if (healthPercent > 0.3) healthColor = '#ff6600';
        
        ctx.fillStyle = healthColor;
        ctx.fillRect(barX + 2, barY + 2, (barWidth - 4) * healthPercent, barHeight - 4);
        
        // 边框
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 2;
        ctx.strokeRect(barX, barY, barWidth, barHeight);
        
        // BOSS等级显示
        ctx.fillStyle = '#ffffff';
        ctx.font = 'bold 16px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`BOSS LV.${this.level}`, this.x + this.width/2, this.y - 30);
        ctx.fillText(`${this.hp}/${this.maxHp}`, this.x + this.width/2, this.y - 45);
    }
}